package com.exam.demo.controller.book;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.exam.demo.domain.Book;
import com.exam.demo.domain.Rent;
import com.exam.demo.domain.User;
import com.exam.demo.mapper.BookMapper;
import com.exam.demo.mapper.RentMapper;
import com.exam.demo.mapper.UserMapper;
import com.exam.demo.result.R;
import com.exam.demo.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    BookMapper baseMapper;

    @Autowired
    RentMapper rentMapper;

    @RequestMapping("/add")
    public R<String> add(@RequestBody Book book){
        //需要不重复的增删改查则加这一句
        /*if(!baseMapper.getUserByName(book).isEmpty()) return R.fail("该用户名已存在");*/
        return R.judge(baseMapper.insert(book)>0);
    }

    @RequestMapping("/del")
    public R<String>  del(@RequestBody Book book){
        return R.judge(baseMapper.deleteById(book.getId())>0);
    }


    @RequestMapping("/getInfo")
    public R<Book>  getInfo(@RequestBody Book book){
        return R.ok(baseMapper.selectById(book.getId()));
    }


    @RequestMapping("/edit")
    public R<String>  edit(@RequestBody Book book){
        return R.judge(baseMapper.updateById(book)>0);
    }


    @RequestMapping("/list")
    public R<List<Book>> list(@RequestBody Book book){
        QueryWrapper<Book> qw = new QueryWrapper<>();
        //如果需要查询条件则在这里加
        qw.like(StringUtils.isNotEmpty(book.getName()),"name",book.getName());
        return R.ok(baseMapper.selectList(qw));
    }


    @RequestMapping("/rent")
    public R<String> rent(@RequestBody Rent rent){

        Boolean result = false;
        //库存--
        Book book = new Book();
        book.setId(rent.getLinkId());
        result = baseMapper.rentBook(book) >0;

        if(result) result = rentMapper.insert(rent) >0 ;
        return R.judge(result);
    }

    @RequestMapping("/rentList")
    public R<List<Rent>> rentList(@RequestBody Book book){
        QueryWrapper<Rent> qw = new QueryWrapper<>();
        //如果需要查询条件则在这里加
        qw.eq(book.getId() != null,"link_id",book.getId());
        return R.ok(rentMapper.selectList(qw));
    }


    @RequestMapping("/back")
    public R<String> back(@RequestBody Rent rent) {

        Boolean result = false;
        rent.setRentBack(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        result = rentMapper.updateById(rent) > 0;

        //库存++
        if (result){
            Book book = new Book();
            book.setId(rent.getLinkId());
            result = baseMapper.backBook(book) > 0;
        }

        return R.judge(result);
    }






}
